import { exportMindMapToGmind } from './index'
import { generateRandomId, setJsonUniqueId } from '../utils'

const JSZip = require('jszip')
const zip = new JSZip()

export async function downloadLocalFile (name, data) {
  if (window.showSaveFilePicker) {
    try {
      const fileHandle = await window.showSaveFilePicker({
        types: [
          {
            description: '',
            accept: { 'application/json': ['.gmind'] }
          }
        ],
        suggestedName: `${name}`
      })
      if (!fileHandle) return
      const copydata = JSON.parse(JSON.stringify(data))
      copydata.id = generateRandomId()
      setJsonUniqueId(copydata.rootTopic, true)
      const content = JSON.stringify(copydata)
      zip.file('content.json', content)
      const binaryData = await zip.generateAsync({ type: 'uint8array' })
      const writable = await fileHandle.createWritable()
      await writable.write(binaryData)
      await writable.close()
    } catch (error) {}
  } else {
    exportMindMapToGmind(name, data)
  }
}
